// src/pages/Home/DataSourceManagement/index.js
import React, { useState } from 'react';
import {
  Table, Card, Button, Modal, Form, Input,
  Upload, message, Divider, Drawer, Tag, Space, Tabs
} from 'antd';
import {
  UploadOutlined,
  FileExcelOutlined,
  FileTextOutlined,
  DatabaseOutlined,
  EditOutlined,
  EyeOutlined,
  SyncOutlined
} from '@ant-design/icons';
import * as XLSX from 'xlsx';
import Papa from 'papaparse';
import RealTimeDataUpdate from './RealTimeDataUpdate';

const { TabPane } = Tabs;

const DataSourceManagement = () => {
  const [dataSources, setDataSources] = useState([]);
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [isDrawerVisible, setIsDrawerVisible] = useState(false);
  const [selectedTable, setSelectedTable] = useState(null);
  const [form] = Form.useForm();
  const [fileList, setFileList] = useState([]);
  const [previewData, setPreviewData] = useState([]);
  const [activeTab, setActiveTab] = useState('dataSources');

  const handleUpload = ({ file, fileList: newFileList }) => {
    setFileList(newFileList);

    if (file.status === 'done') {
      message.success(`${file.name} 文件上传成功`);
      parseFile(file.originFileObj);
    } else if (file.status === 'error') {
      message.error(`${file.name} 文件上传失败`);
    }
  };

  const parseFile = (file) => {
    const fileName = file.name.toLowerCase();

    if (fileName.endsWith('.csv')) {
      parseCSV(file);
    } else if (fileName.endsWith('.xlsx') || fileName.endsWith('.xls')) {
      parseExcel(file);
    } else {
      message.error('只支持 CSV、XLSX 或 XLS 格式的文件');
    }
  };

  const parseCSV = (file) => {
    Papa.parse(file, {
      complete: (results) => {
        if (results.data && results.data.length > 0) {
          const headers = results.data[0];
          const rows = results.data.slice(1);

          const tableData = rows.map((row, index) => {
            const rowData = {};
            headers.forEach((header, i) => {
              rowData[header] = row[i] || '';
            });
            return { key: index, ...rowData };
          });

          setPreviewData({
            headers,
            data: tableData.slice(0, 5), // 只预览前5行
            rowCount: rows.length
          });
        }
      },
      header: false,
      skipEmptyLines: true
    });
  };

  const parseExcel = (file) => {
    const reader = new FileReader();
    reader.onload = (e) => {
      const data = new Uint8Array(e.target.result);
      const workbook = XLSX.read(data, { type: 'array' });

      const firstSheetName = workbook.SheetNames[0];
      const worksheet = workbook.Sheets[firstSheetName];
      const jsonData = XLSX.utils.sheet_to_json(worksheet, { header: 1 });

      if (jsonData && jsonData.length > 0) {
        const headers = jsonData[0];
        const rows = jsonData.slice(1);

        const tableData = rows.map((row, index) => {
          const rowData = {};
          headers.forEach((header, i) => {
            rowData[header] = row[i] || '';
          });
          return { key: index, ...rowData };
        });

        setPreviewData({
          headers,
          data: tableData.slice(0, 5), // 只预览前5行
          rowCount: rows.length
        });
      }
    };
    reader.readAsArrayBuffer(file);
  };

  const handleCreateDataSource = () => {
    form.validateFields().then(values => {
      if (fileList.length === 0) {
        message.error('请先上传文件');
        return;
      }

      const newDataSource = {
        id: Date.now().toString(),
        name: values.name,
        fileName: fileList[0].name,
        type: getFileType(fileList[0].name),
        createdAt: new Date().toLocaleString(),
        rowCount: previewData.rowCount || 0,
        columnCount: previewData.headers ? previewData.headers.length : 0,
        description: values.description || ''
      };

      setDataSources([...dataSources, newDataSource]);
      message.success('数据源创建成功');
      setIsModalVisible(false);
      form.resetFields();
      setFileList([]);
    });
  };

  const getFileType = (fileName) => {
    if (fileName.endsWith('.csv')) return 'CSV';
    if (fileName.endsWith('.xlsx')) return 'Excel (XLSX)';
    if (fileName.endsWith('.xls')) return 'Excel (XLS)';
    return 'Unknown';
  };

  const handleViewDetails = (record) => {
    setSelectedTable(record);
    setIsDrawerVisible(true);
  };

  const handleEdit = (record) => {
    // 这里可以实现编辑功能
    message.info('编辑功能待实现');
  };

  const columns = [
    {
      title: '数据表名称',
      dataIndex: 'name',
      key: 'name',
      render: (text, record) => (
        <Space>
          {record.type === 'CSV' ? <FileTextOutlined /> : <FileExcelOutlined />}
          {text}
        </Space>
      )
    },
    {
      title: '文件名',
      dataIndex: 'fileName',
      key: 'fileName',
    },
    {
      title: '类型',
      dataIndex: 'type',
      key: 'type',
      render: (type) => (
        <Tag color={type === 'CSV' ? 'blue' : 'green'}>
          {type}
        </Tag>
      )
    },
    {
      title: '行数',
      dataIndex: 'rowCount',
      key: 'rowCount',
    },
    {
      title: '列数',
      dataIndex: 'columnCount',
      key: 'columnCount',
    },
    {
      title: '创建时间',
      dataIndex: 'createdAt',
      key: 'createdAt',
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space size="middle">
          <Button
            type="link"
            icon={<EyeOutlined />}
            onClick={() => handleViewDetails(record)}
          >
            查看详情
          </Button>
          <Button
            type="link"
            icon={<EditOutlined />}
            onClick={() => handleEdit(record)}
          >
            编辑
          </Button>
        </Space>
      ),
    },
  ];

  const renderDataSources = () => (
    <div>
      <Card
        title={
          <Space>
            <DatabaseOutlined />
            数据源管理
          </Space>
        }
        extra={
          <Button
            type="primary"
            onClick={() => setIsModalVisible(true)}
          >
            导入数据表
          </Button>
        }
      >
        <Table
          dataSource={dataSources}
          columns={columns}
          rowKey="id"
        />
      </Card>

      <Modal
        title="导入数据表"
        open={isModalVisible}
        onCancel={() => {
          setIsModalVisible(false);
          form.resetFields();
          setFileList([]);
        }}
        onOk={handleCreateDataSource}
        width={600}
      >
        <Form form={form} layout="vertical">
          <Form.Item
            name="name"
            label="数据表名称"
            rules={[{ required: true, message: '请输入数据表名称' }]}
          >
            <Input placeholder="例如：销售数据表" />
          </Form.Item>

          <Form.Item
            name="description"
            label="描述"
          >
            <Input.TextArea placeholder="数据表的简要描述" />
          </Form.Item>

          <Form.Item
            label="上传文件"
            rules={[{ required: true, message: '请上传文件' }]}
          >
            <Upload
              fileList={fileList}
              onChange={handleUpload}
              beforeUpload={() => false} // 阻止自动上传
              accept=".csv,.xlsx,.xls"
            >
              <Button icon={<UploadOutlined />}>选择文件</Button>
            </Upload>
            <p style={{ marginTop: 8, color: '#999' }}>
              支持 CSV、XLSX、XLS 格式
            </p>
          </Form.Item>

          {previewData.headers && (
            <div>
              <Divider>数据预览</Divider>
              <p>共 {previewData.rowCount} 行，{previewData.headers.length} 列</p>
              <Table
                dataSource={previewData.data}
                columns={previewData.headers.map(header => ({
                  title: header,
                  dataIndex: header,
                  key: header,
                }))}
                pagination={false}
                size="small"
                scroll={{ x: true }}
              />
            </div>
          )}
        </Form>
      </Modal>

      <Drawer
        title="数据表详情"
        placement="right"
        onClose={() => setIsDrawerVisible(false)}
        open={isDrawerVisible}
        width={600}
      >
        {selectedTable && (
          <div>
            <Card size="small" title="基本信息">
              <p><strong>数据表名称:</strong> {selectedTable.name}</p>
              <p><strong>文件名:</strong> {selectedTable.fileName}</p>
              <p><strong>类型:</strong> {selectedTable.type}</p>
              <p><strong>行数:</strong> {selectedTable.rowCount}</p>
              <p><strong>列数:</strong> {selectedTable.columnCount}</p>
              <p><strong>创建时间:</strong> {selectedTable.createdAt}</p>
              {selectedTable.description && (
                <p><strong>描述:</strong> {selectedTable.description}</p>
              )}
            </Card>

            <Card size="small" title="字段信息" style={{ marginTop: 16 }}>
              {previewData.headers ? (
                <Table
                  dataSource={previewData.headers.map((header, index) => ({
                    key: index,
                    name: header,
                    type: 'string', // 简化处理，实际项目中可以更精确地推断类型
                    description: ''
                  }))}
                  columns={[
                    { title: '字段名', dataIndex: 'name', key: 'name' },
                    { title: '类型', dataIndex: 'type', key: 'type' },
                    { title: '描述', dataIndex: 'description', key: 'description' },
                  ]}
                  pagination={false}
                  size="small"
                />
              ) : (
                <p>暂无字段信息</p>
              )}
            </Card>
          </div>
        )}
      </Drawer>
    </div>
  );

  return (
    <div style={{ padding: '24px' }}>
      <Tabs
        activeKey={activeTab}
        onChange={setActiveTab}
        items={[
          {
            key: 'dataSources',
            label: (
              <span>
                <DatabaseOutlined />
                数据源管理
              </span>
            ),
            children: renderDataSources(),
          },
          {
            key: 'realTime',
            label: (
              <span>
                <SyncOutlined />
                实时数据更新
              </span>
            ),
            children: <RealTimeDataUpdate />,
          },
        ]}
      />
    </div>
  );
};

export default DataSourceManagement;
